package cn.xt.util;

import org.apache.commons.io.FilenameUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;

public class FileImageUtils {
    public static String ImageFile(HttpServletRequest request,MultipartFile attach){
        String idPicPath=null;
        if(attach!=null){
            /*保存路径*/
            String path = request.getServletContext().getRealPath("/statics/fileUplodaImage");
           // String path="D:\\workspace\\ess\\ysshortrental\\src\\main\\webapp\\statics\\fileUplodaImage";
            /*原文件名*/
            String oldFileName=attach.getOriginalFilename();
            System.out.println("源文件名"+oldFileName);
            /*文件名后缀*/
            String suffix= FilenameUtils.getExtension(oldFileName);
            System.out.println("源文件名的扩展名="+suffix);
            /*文件大小*/
            int fileSize=31457280;
            System.out.println("上传文件的字节数"+attach.getSize());
            if(attach.getSize()>fileSize){
                System.out.println("上传大小不的超过3MKB");
                // request.setAttribute("uploadFileError","上传大小不的超过500KB");
                return "Image";
            }else if (suffix.equalsIgnoreCase("png")||
                    suffix.equalsIgnoreCase("jpeg")||
                    suffix.equalsIgnoreCase("jpg"))
                /*系统的当前信息*/ {
                String filename=System.currentTimeMillis()+"yuansu"+"_Personal." + suffix;

                File targetFile=new File(path,filename);
                try {
                    if(targetFile.isFile()){
                        System.out.println("文件已经创建");
                    }else {
                        //这里为什么要用getParentFile()，不能直接mkdirs() ？
                        targetFile.getParentFile().mkdirs();
                        //f.mkdirs();
                        try{
                            targetFile.createNewFile();
                        }catch(IOException ex){
                            ex.printStackTrace();
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                /*项目缓存的文件移动到目标*/
                try {
                    attach.transferTo(targetFile);
                } catch (IOException e) {
                    e.printStackTrace();
                    System.out.println("上传文件的失败");
                    request.setAttribute("uploadFileError","上传文件的失败");
                    return "Image1";
                }
                idPicPath=filename;
            }
            else {
                System.out.println("上传文件的格式不正确");
                request.setAttribute("uploadFileError","上传文件的格式不正确");
                return "";
            }
        }
        return idPicPath;
    }
}

